const Koa = require('koa')
const next = require('next')
const Router = require('koa-router')
const Redis  = require('koa-redis')
const session = require('koa-session')
const json = require('koa-json')
const bodyParser = require('koa-bodyparser')
const atob = require('atob')
const RedisSessionStore = require('./redis')
const auth = require('./auth')
const api = require('./api')
//开发状态
const port = 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
//http响应
const handle = app.getRequestHandler()
//设置全局atob方法
global.atob = atob
//页面编译完成后响应请求
app.prepare().then(()=>{
  const server = new Koa()
  const router = new Router()
  server.proxy = true
  server.use(bodyParser({
    entableTypes: ['json','form','text']
  }))
  server.use(json())
  
    //配置session
  const REDIS_CONFIG = {
    port: 6379,
    host: '127.0.0.1'
  }
  const SESSION_CONFIG = {
    key:'user',
    maxAge:  24 * 60 * 60 * 1000,
    store: new RedisSessionStore(new Redis(REDIS_CONFIG))
  }
  server.keys= ['_ayuan#']
  server.use(session(SESSION_CONFIG,server))
  
  //处理github auth
  auth(server)
  api(server)
  
  router.get('/api/getUserInfo',async (ctx, next) => {
    const user = ctx.session.userInfo
    if(!user) {
      ctx.state = 401
      ctx.body = 'Need Login'
    }
    ctx.body = user
  })
  
  router.post('/api/logout', async (ctx, next) => {
    ctx.session = null
    ctx.body = 'logout success'
  })
  
  router.get('/prepare-auth', async (ctx) => {
    //拿到路由地址记录在session中
    const { url } = ctx.query
    ctx.session.urlBeforeAuth = url
    ctx.body = 'success'
  })
  server.use(router.routes())
  //监听
  server.use(async (ctx,next) => {
    ctx.req.session = ctx.session
    await handle(ctx.req, ctx.res)
    //不处理返回响应
    ctx.respond = false
  })
  server.listen(port,() => {
    console.log(`server is running on ${port}`)
  })
})
